package cn.drenal.capcap.controller.forum;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.drenal.capcap.common.Response;
import cn.drenal.capcap.entity.*;
import cn.drenal.capcap.entity.vo.forum.ForumActivityVO;
import cn.drenal.capcap.entity.vo.forum.ForumArtworkCardVO;
import cn.drenal.capcap.entity.vo.forum.ForumSearchResultVO;
import cn.drenal.capcap.mapper.*;
import cn.drenal.capcap.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 论坛搜索控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/forum/search")
public class ForumSearchController {

    private final ArtworkMapper artworkMapper;

    private final UserMapper userMapper;

    private final ActivityMapper activityMapper;

    private final UserService userService;

    private final TagMapper tagMapper;

    private final ArtworkTagMapper artworkTagMapper;

    /**
     * 根据关键字搜索
     * 
     * @param keyword 搜索关键字
     * @param type 搜索类型：0-作品名，1-作者名，2-活动名
     * @param current 当前页码
     * @param size 每页大小
     * @return 搜索结果
     */
    @SaIgnore
    @GetMapping
    public Response<ForumSearchResultVO> search(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") Integer type,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        ForumSearchResultVO resultVO = new ForumSearchResultVO();
        
        // 根据搜索类型执行不同的搜索逻辑
        switch (type) {
            case 0: // 搜索作品名
                searchArtworks(keyword, current, size, resultVO);
                break;
            case 1: // 搜索作者名
                searchByAuthor(keyword, current, size, resultVO);
                break;
            case 2: // 搜索活动名
                searchActivities(keyword, current, size, resultVO);
                break;
            default:
                return Response.error("不支持的搜索类型");
        }
        
        return Response.success(resultVO);
    }
    
    /**
     * 搜索作品
     */
    private void searchArtworks(String keyword, Integer current, Integer size, ForumSearchResultVO resultVO) {
        // 构建作品名称查询条件
        LambdaQueryWrapper<Artwork> titleQueryWrapper = new LambdaQueryWrapper<>();
        titleQueryWrapper.like(Artwork::getTitle, keyword)
                .eq(Artwork::getStatus, 2) // 只搜索已发布的作品(状态为2)
                .orderByDesc(Artwork::getCreateTime);
        
        // 查找包含匹配标签名的作品ID
        LambdaQueryWrapper<Tag> tagQueryWrapper = new LambdaQueryWrapper<>();
        tagQueryWrapper.like(Tag::getName, keyword);
        List<Tag> matchedTags = tagMapper.selectList(tagQueryWrapper);
        
        List<String> artworkIdsFromTags = new ArrayList<>();
        if (!matchedTags.isEmpty()) {
            List<String> tagIds = matchedTags.stream()
                    .map(tag -> tag.getId().toString())
                    .collect(Collectors.toList());
            
            LambdaQueryWrapper<ArtworkTag> artworkTagQueryWrapper = new LambdaQueryWrapper<>();
            artworkTagQueryWrapper.in(ArtworkTag::getTagId, tagIds);
            artworkIdsFromTags = artworkTagMapper.selectList(artworkTagQueryWrapper)
                    .stream()
                    .map(ArtworkTag::getArtworkId)
                    .collect(Collectors.toList());
        }
        
        // 如果找到了匹配标签的作品，添加到查询条件中
        if (!artworkIdsFromTags.isEmpty()) {
            titleQueryWrapper.or()
                    .in(Artwork::getId, artworkIdsFromTags)
                    .eq(Artwork::getStatus, 2);
        }
        
        // 执行分页查询
        Page<Artwork> page = new Page<>(current, size);
        Page<Artwork> artworkPage = artworkMapper.selectPage(page, titleQueryWrapper);
        
        // 转换为VO对象
        List<ForumArtworkCardVO> artworkVOList = artworkPage.getRecords().stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            BeanUtils.copyProperties(artwork, vo);
            
            // 设置作者名称
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        // 设置结果
        resultVO.setArtworks(artworkVOList);
        resultVO.setTotal(artworkPage.getTotal());
        resultVO.setType(0);
    }
    
    /**
     * 根据作者名搜索作品
     */
    private void searchByAuthor(String keyword, Integer current, Integer size, ForumSearchResultVO resultVO) {
        // 先查找匹配的用户
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.like(User::getUsername, keyword);
        List<User> users = userMapper.selectList(userQueryWrapper);
        
        if (users.isEmpty()) {
            // 没有找到匹配的用户
            resultVO.setArtworks(List.of());
            resultVO.setTotal(0L);
            resultVO.setType(1);
            return;
        }
        
        // 获取用户ID列表
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        
        // 查询这些用户的作品
        LambdaQueryWrapper<Artwork> artworkQueryWrapper = new LambdaQueryWrapper<>();
        artworkQueryWrapper.in(Artwork::getUserId, userIds)
                .eq(Artwork::getStatus, 2) // 只搜索已发布的作品(状态为2)
                .orderByDesc(Artwork::getCreateTime);
        
        // 执行分页查询
        Page<Artwork> page = new Page<>(current, size);
        Page<Artwork> artworkPage = artworkMapper.selectPage(page, artworkQueryWrapper);
        
        // 转换为VO对象
        List<ForumArtworkCardVO> artworkVOList = artworkPage.getRecords().stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            BeanUtils.copyProperties(artwork, vo);
            
            // 设置作者名称
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        // 设置结果
        resultVO.setArtworks(artworkVOList);
        resultVO.setTotal(artworkPage.getTotal());
        resultVO.setType(1);
    }
    
    /**
     * 搜索活动
     */
    private void searchActivities(String keyword, Integer current, Integer size, ForumSearchResultVO resultVO) {
        // 构建查询条件
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Activity::getName, keyword)
                .orderByDesc(Activity::getCreateTime);
        
        // 执行分页查询
        Page<Activity> page = new Page<>(current, size);
        Page<Activity> activityPage = activityMapper.selectPage(page, queryWrapper);
        
        // 转换为VO对象
        List<ForumActivityVO> activityVOList = activityPage.getRecords().stream().map(activity -> {
            ForumActivityVO vo = new ForumActivityVO();
            BeanUtils.copyProperties(activity, vo);
            return vo;
        }).collect(Collectors.toList());
        
        // 设置结果
        resultVO.setActivities(activityVOList);
        resultVO.setTotal(activityPage.getTotal());
        resultVO.setType(2);
    }
}